import { Header } from '@/components/Header';
import { SnippetCard } from '@/components/SnippetCard';
import { getSnippets, getTags } from '@/services/api';
import { Snippet } from '@/types';
import Link from 'next/link';

interface HomeProps {
  searchParams: { [key: string]: string | string[] | undefined };
}

export default async function Home({ searchParams:_searchParams }: HomeProps) {

  const searchParams = await _searchParams;

  const page = typeof searchParams.page === 'string' ? Number(searchParams.page) : 1;
  const tag = typeof searchParams.tag === 'string' ? searchParams.tag : undefined;

  const [{ snippets, total }, tags] = await Promise.all([
    getSnippets(page, 10, tag),
    getTags(),
  ]);

  const hasMore = page * 10 < total;

  return (
    <div className="flex flex-col min-h-screen bg-gray-50 dark:bg-gray-900">
      <Header />
      <main className="flex-1 container mx-auto py-8 px-4 md:px-6">
        <div className="flex flex-col md:flex-row gap-8">
          <div className="w-full md:w-1/4">
            <div className="bg-white dark:bg-gray-950 rounded-xl shadow-lg p-6">
              <h2 className="text-lg font-semibold mb-4">Tags</h2>
              <div className="flex flex-wrap gap-2">
                <Link href={'/'}>
                   <span className={`bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-300 px-3 py-1 rounded-full text-sm font-medium ${!tag ? 'ring-2 ring-blue-500' : ''}`}>All</span>
                </Link>
                {tags.map(t => (
                  <Link href={`/?tag=${t.name}`} key={t.id}>
                    <span className={`bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-300 px-3 py-1 rounded-full text-sm font-medium ${tag === t.name ? 'ring-2 ring-blue-500' : ''}`}>{t.name}</span>
                  </Link>
                ))}
              </div>
            </div>
          </div>
          <div className="w-full md:w-3/4">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {snippets.map(snippet => (
                <SnippetCard key={snippet.id} snippet={snippet} />
              ))}
            </div>
            {hasMore && (
              <div className="flex justify-center mt-8">
                <Link
                  href={`/?page=${page + 1}${tag ? `&tag=${tag}`: ''}`}
                  className="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg transition-colors duration-300"
                  prefetch={false}
                >
                  Load More
                </Link>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
